<template>
  <el-form ref="deptForm" :model="form" :rules="formRules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input
        v-model="form.name"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input
        v-model="form.code"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width: 80%" placeholder="请选择">
        <el-option
          v-for="item in list"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input
        v-model="form.introduce"
        style="width: 80%"
        placeholder="1-300个字符"
        type="textarea"
        :rows="3"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeesSimples } from '@/api/empioyees'
import {
  addDepartments,
  getDepartmentDetail,
  updateDepartment
} from '@/api/departments'

export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 自定义校验,验证部门编码的唯一性
    const validCode = (rule, value, callback) => {
      // 取出originList中的code
      let existCodeList = this.originList.map((item) => item.code)
      console.log(existCodeList, 'existCodeList')

      // 如果是编辑状态,则将当前编辑部门的数据从存储的数据中删除,在进行判断
      if (this.isEdit) {
        existCodeList = this.originList
          .filter((item) => item.id !== this.id)
          .map((item) => item.code)
      }

      // 筛选当前value是否存在
      if (existCodeList.includes(value)) {
        callback(new Error(`该部门编码${value}已存在`))
      } else {
        callback()
      }
    }

    // 自定义校验,验证部门名称,同级不能重复
    const validName = (rule, value, callback) => {
      // 筛选出pid与id相等的数据,再取出部门名称
      let existNameList = this.originList
        .filter((item) => item.pid === this.id)
        .map((item) => item.name)
      console.log(existNameList, 'existNameList')

      if (this.isEdit) {
        // 获取编辑页面 当前部门的pid
        const pid = this.originList.find(item => item.id === this.id).pid
        // 通过pid查找所有部门数据中的同级
        const brothers = this.originList.filter(item => item.pid === pid)
        // 排除自己,重新赋值
        existNameList = brothers.filter(item => item.id !== this.id).map(item => item.name)
      }

      if (existNameList.includes(value)) {
        callback(new Error(`该部门名称${value}已存在`))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      formRules: {
        name: [
          { required: true, message: '请输入部门名称', tigger: 'blur' },
          { min: 1, max: 50, message: '请输入1-50个字符', tigger: 'blur' },
          { validator: validName, tigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', tigger: 'blur' },
          { min: 1, max: 50, message: '请输入1-50个字符', tigger: 'blur' },
          { validator: validCode, tigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门负责人', tigger: 'change' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', tigger: 'blur' },
          { min: 1, max: 300, message: '请输入1-300个字符', tigger: 'blur' }
        ]
      },
      list: []
    }
  },
  // watch: {
  //   id: function(new_val, old_val) {
  //     // 解决数据不更新的第三种方法
  //     this.loadDepartmentDetail()
  //   }
  // },
  created() {
    // 数据渲染前触发事件发送ajax
    this.laodEmployeesSimples()
    // 当弹层框是编辑页面的时候触发
    if (this.isEdit) {
      // 获取部门详细信息
      this.loadDepartmentDetail()
    }
  },
  methods: {
    // 获取部门负责人信息
    async laodEmployeesSimples() {
      try {
        // 调用发送ajax的封装函数
        const res = await getEmployeesSimples()
        console.log(res, '部分负责人')
        // 获取到的数据存储到list
        this.list = res.data
      } catch (error) {
        console.log(error)
      }
    },

    // 获取部门详细信息
    async loadDepartmentDetail() {
      try {
        // 调用发送ajax的封装函数
        const res = await getDepartmentDetail(this.id)
        console.log(res, '部门详情数据')
        // 获取部门详细信息
        this.form = res.data
      } catch (error) {
        console.log(error)
      }
    },

    // 新增部门
    async doAdd() {
      // 发送ajax
      try {
        // 发送请求
        const res = await addDepartments({ pid: this.id, ...this.form })
        // 如果添加失败提示错误
        if (!res.success) return this.$message.error(res.message)

        // 子传父进行数据渲染及关闭弹层
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },

    // 修改部门
    async doEdit() {
      // 发送ajax
      try {
        // 发送请求
        const res = await updateDepartment(this.form)
        // 如果添加失败提示错误
        if (!res.success) return this.$message.error(res.message)

        // 子传父进行数据渲染及关闭弹层
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 取消关闭弹层
    hCancel() {
      this.$emit('close')
    },

    hSubmit() {
      // 表单兜底校验
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return // 校验失败
        // 实现编辑部门或者新增子部门的事件
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },

    // 解决数据不更新的方法3
    resetForm() {
      // this.$refs.deptForm.resetFields()
      console.log('解决数据不更新的方法3', '子组件')
    }
  }
}
</script>

<style>
</style>
